package com.imooc.annotation_demo.utils;

import com.imooc.annotation_demo.annotations.Column;
import com.imooc.annotation_demo.annotations.Table;
import com.imooc.annotation_demo.filters.UserFilter;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class QueryUtils {

    public static String querySql(Object filter) {
        //1.确定表名
        Class c = filter.getClass();
        String strTableName = null;
        if (!c.isAnnotationPresent(Table.class)) {
            return null;
        }
        Table table = (Table) c.getAnnotation(Table.class);
        strTableName = table.value();

        StringBuilder sbSql = new StringBuilder("select * from " + strTableName + " where 1=1 ");

        //2.确定查询条件
        Field[] fieldArray = c.getDeclaredFields();
        for (Field field : fieldArray) {
            //1.条件判断:注解与value不能为空
            if (!field.isAnnotationPresent(Column.class)) {
                continue;
            }
            String getMethodName = BeanUtil.calcGetMethodName(field.getName());
            Object getValue = null;
            try {
                Method getMethod = c.getMethod(getMethodName);
                getValue = getMethod.invoke(filter);
                if (getValue == null) {
                    continue;
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }


            Column column = field.getAnnotation(Column.class);
            Class fc = field.getType();
            switch (fc.getSimpleName()) {
                case "String":
                    sbSql.append("and " + column.value() + "='" + getValue + "' ");
                    break;
                case "Integer":
                case "Long":
                case "Boolean":
                    sbSql.append("and " + column.value() + "=" + getValue + " ");
                    break;
                default:
                    sbSql.append("and " + column.value() + "='" + getValue + "' ");
                    break;
            }


        }

        return sbSql.toString();
    }
}
